﻿using System;

namespace DotNetCommon.Validate.Annotations;

/// <summary>
/// 限制字符串长度范围, 示例:
/// <code>
/// [VDisplayName("姓名")]
/// [VLengthInRange(2, 4)]
/// public string Name { get; set; }
/// </code>
/// </summary>
/// <remarks>注意: 当属性不是字符串时, 会先调用 ToString() 转为字符串再进行判断, 这可以用于对非字符串类型的校验</remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VLengthInRangeAttribute(int min, int max, string errorMessage = null) : Attribute, IValidateAction
{
    public int Min { get; set; } = min;
    public int Max { get; set; } = max;
    public string ErrorMessage { get; set; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        ValidateStringExtensions.MustLengthInRangeInternal(ctx, ctx.ModelValue?.ToString(), Min, Max, ErrorMessage);
    }
}

/// <summary>
/// 如果不为null, 则限制字符串长度范围, 示例:
/// <code>
/// [VDisplayName("姓名")]
/// [VLengthInRangeIfNotNull(2, 4)]
/// public string Name { get; set; }
/// </code>
/// </summary>
/// <remarks>注意: 当属性不是字符串时, 会先调用 ToString() 转为字符串再进行判断, 这可以用于对非字符串类型的校验</remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VLengthInRangeIfNotNullAttribute(int min, int max, string errorMessage = null) : Attribute, IValidateAction
{
    public int Min { get; set; } = min;
    public int Max { get; set; } = max;
    public string ErrorMessage { get; set; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        if (ctx.ModelValue == null) return;
        ValidateStringExtensions.MustLengthInRangeInternal(ctx, ctx.ModelValue?.ToString(), Min, Max, ErrorMessage);
    }
}
